/**
 * 
 */
package com.study.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author Administrator
 * @date 2019年6月16日
 */
public class PoolThreadDemo {
	private static int POOL_NUM = 10; // 线程池数量

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		//ExecutorService executorService = Executors.newFixedThreadPool(3);  //线程池数为3
		ExecutorService executorService = Executors.newCachedThreadPool();
		for(int i = 0; i < POOL_NUM; i++) {
			RunnableThread1 thread = new RunnableThread1();
			executorService.execute(thread);
		}
		
		//ExecutoreService提供了submit()方法，传递一个Callable，或Runnable，返回Future。
		Future<Integer> future = executorService.submit(new Callable<Integer>(){
			@Override
			public Integer call() throws Exception {
				int sum = 0;
				for(int i=0;i<5;i++){
					sum = sum + i;
				}
				return sum;
			}
			
		});
		System.out.println("before future.get()..");
		System.out.println("future.get():" + future.get());  //阻塞等待结果
		System.out.println("after future.get()..");
		
		// 关闭线程池
		System.out.println("主程序结束。。");
		executorService.shutdown();
	}
}

class RunnableThread1 implements Runnable {
	@Override
	public void run() {
		System.out.println("通过线程池方式创建的线程：" + Thread.currentThread().getName() + " ");
	}
}